package exam.shenxinfu.S3;


import util.ListNode;

public class Solution {

    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode p = dummy;
        while (p.next != null) {
            if (p.next.val == 3)
                break;
            p = p.next;
        }
        if (p.next == null)
            return dummy.next;
        ListNode q = p;
        int k = 0;
        while (q != null) {
            if (q.val == 6) {
                break;
            }
            q = q.next;
            k++;
        }
        if (q == null)
            return dummy.next;
        ListNode tHead = reverse(p.next, k);
        p.next = tHead;
        return dummy.next;
    }

    private ListNode reverse(ListNode head, int k) {
        if (k == 1)
            return head;
        ListNode tHead = reverse(head.next, k-1);
        ListNode tail = head.next;
        head.next = tail.next;
        tail.next = head;
        return tHead;
    }
}